########################################################################################################### 
##### Descriptive Figures (1-3): Data Section
###########################################################################################################

##Loading packages
rm(list = ls())
library(plyr)
library(dplyr)
library(ggplot2)
library(data.table)
library(caTools)
library(haven)
library(readr)
library(dummies)
library(lubridate)
library(fixest)
library(readstata13)
library(robustHD)
library(AER)
library(stdidx)
library(jtools)
library(MASS)
library(mosaic)
library(sensemakr)
library(ggpubr)
library(stdidx)

#Set working directory
setwd("")

#Load data
data <- read_dta("data_2rounds.dta")
data$roundf <- as.factor(data$round)

############# Figure (1)

#Panel (a): Total violence

allplot <- gghistogram(data, x = "allintimid", bins = 200, 
                       color = "roundf", fill="roundf", 
                       add = "mean", rug = TRUE, 
                       palette = c("#0073C2FF", "#FC4E07"), 
                       xlab="Number of Acts", ylab="Count")+ theme(legend.position="none")


#Panel (b): Violence against voters

voterplot <- gghistogram(data, x = "voter_total", bins = 200, 
                         color = "roundf", fill="roundf", 
                         add = "mean", rug = TRUE, 
                         palette = c("#0073C2FF", "#FC4E07"), 
                         xlab="Number of Acts", ylab="Count")+ theme(legend.position="none")


#Panel (c): Violence by state actors

stateplot <- gghistogram(data, x = "state_intimidation", bins = 200, 
                         color = "roundf", fill="roundf", 
                         add = "mean", rug = TRUE, 
                         palette = c("#0073C2FF", "#FC4E07"), 
                         xlab="Number of Acts", ylab="Count")+ theme(legend.position="none")


#Panel (d): Violence by non-state actors

nonstateplot <- gghistogram(data, x = "nonstate_intimidation", bins = 200, 
                            color = "roundf", fill="roundf", 
                            add = "mean", rug = TRUE, 
                            palette = c("#0073C2FF", "#FC4E07"), 
                            xlab="Number of Acts", ylab="Count")+ theme(legend.position="none")


############ Figure (2)

#First, we aggregate all violent incidents for each district
temp <- data[,c("allintimid", "voter_total", "state_intimidation", "nonstate_intimidation", "district_name", "phase")] 

agg_data <- temp %>%
  group_by(data$district_name) %>%
  summarize(allintimid=sum(allintimid), 
            voter_total=sum(voter_total),
            state_intimidation=sum(state_intimidation),
            nonstate_intimidation=sum(nonstate_intimidation), 
            phase=first(phase))

agg_data$phase <- as.factor(agg_data$phase)

#Then, we construct the density plots

#Panel (a): Total violence

dallplot <- ggdensity(agg_data, x = "allintimid",
                      add = "mean", rug = TRUE,
                      color = "phase", fill = "phase",
                      palette = c("#0073C2FF", "#FC4E07", "#EFC000FF"), xlab="", ylab="Density")+ theme(legend.position="none")


#Panel (b): Violence against voters

dvplot <- ggdensity(agg_data, x = "voter_total",
                    add = "mean", rug = TRUE,
                    color = "phase", fill = "phase",
                    palette = c("#0073C2FF", "#FC4E07", "#EFC000FF"), xlab="", ylab="Density")+ theme(legend.position="none")


#Panel (c): Violence by state actors

dstateplot <- ggdensity(agg_data, x = "state_intimidation",
                        add = "mean", rug = TRUE,
                        color = "phase", fill = "phase",
                        palette = c("#0073C2FF", "#FC4E07", "#EFC000FF"), xlab="", ylab="Density")+ theme(legend.position="none")


#Panel (d): Violence by non-state actors

dnstateplot <- ggdensity(agg_data, x = "nonstate_intimidation",
                         add = "mean", rug = TRUE,
                         color = "phase", fill = "phase",
                         palette = c("#0073C2FF", "#FC4E07", "#EFC000FF"), xlab="", ylab="Density")+ theme(legend.position="none")


remove(data)
remove (temp_data)
remove(agg_data)

############## Figure (3)

#Load required packages and shape file for Egypt's administrative units
require(sf)
require(maptools)
require(rgeos)
require(plyr)
library(RColorBrewer)
shape <- read_sf(dsn = "egy_admbnda_adm2_capmas_20170421.shp")

#The next set of steps match the violence data with the spatial variables. However, this requires some adjustments to naming of districts 
# to align the units together (due to different naming conventions between the violence electoral data and the spatial files)


##Import a file where districts' naming is aligned between the shape files and electoral data
namedata <- read.csv("match_names.csv")
names(namedata)[3] <- "ADM2_PCODE"

##Merge this name file with the shape file 
shape2 <- merge(shape, namedata, by=c("ADM2_PCODE"))

#This will collapse the geometries into the districts (including some districts that has no electoral relevance at the time of the election)
shape2_union <- shape2 %>%
  group_by(district_name) %>% 
  summarize(geometry = st_combine(geometry))


#Import the violence data and adjust naming according to the spatial units
data <- read_dta("data_2rounds.dta")

data$district_name[data$district_name=="El-Mahad El-Fany"] <- "Shobra"
data$district_name[data$district_name=="El-Manyal"] <- "Masr El-Qadimah"
data$district_name[data$district_name=="Ghorbal"] <- "Moharam Bek"
data$district_name[data$district_name=="Basandeela"] <- "Belkass"
data$district_name[data$district_name=="Atmeeda"] <- "Meet Ghamr"
data$district_name[data$district_name=="Al-Teleen"] <- "Menia Al-Qamh"
data$district_name[data$district_name=="Ashkor"] <- "Faqous"
data$district_name[data$district_name=="Al-Agouzein"] <- "Disouq"
data$district_name[data$district_name=="Berma"] <- "Tanta"
data$district_name[data$district_name=="Mahala Rouh"] <- "Tanta"
data$district_name[data$district_name=="Beshbeesh"] <- "Markaz Shurta Mahalla al-Kubra"
data$district_name[data$district_name=="Nehtai"] <- "Zefta"
data$district_name[data$district_name=="Batanoun"] <- "Shebeen Al-Koum"
data$district_name[data$district_name=="Istenha"] <- "El-Bagour"
data$district_name[data$district_name=="Shamma"] <- "Ashmoun"
data$district_name[data$district_name=="Mazghouna"] <- "Badrasheen"
data$district_name[data$district_name=="Al-Dowayrat"] <- "Al-Monshaah"
data$district_name[data$district_name=="Al-Ra'eesiya"] <- "Naga' Hamadi"
data$district_name[data$district_name=="Al-Agamiyeen"] <- "Ibshouwai"


subdata<- subset(data, select=c("district_name", "allintimid", "voter_total", 
                                "state_intimidation", "nonstate_intimidation"))

#So, we nonw have the full data (aggregated for the two rounds) that we want to plot
data2rounds <- aggregate(cbind(allintimid, voter_total, state_intimidation, nonstate_intimidation) ~ district_name, subdata, FUN=sum)

#Merge & Map
shape2_union <- merge(shape2_union, data2rounds, by=c("district_name"))
cdata4 <- as(st_as_sf(shape2_union), Class="Spatial")

####### Mapping the data

# Panel (a): Total violence

map1 <- spplot(cdata4, "allintimid", col.regions=c("gray80","grey70", "gray60", "gray50", "gray40","gray30", "gray20", "gray15", "black"), 
               cuts = 8, col = "transparent")

#Panel (b): Violence against voters

map2 <- spplot(cdata4, "voter_total", col.regions=c("gray80","grey70", "gray60", "gray50", "gray40","gray30", "gray20", "gray15", "black"), 
               cuts = 8, col = "transparent")

#Panel (c): Violence by state actors

map3 <- spplot(cdata4, "state_intimidation", col.regions=c("gray80","grey70", "gray60", "gray50", "gray40","gray30", "gray20", "gray15", "black"), 
               cuts = 8, col = "transparent")


#Panel (d): Violence by non-state actors

map4 <- spplot(cdata4, "nonstate_intimidation", col.regions=c("gray80","grey70", "gray60", "gray50", "gray40","gray30", "gray20", "gray15", "black"), 
               cuts = 8, col = "transparent")

